package com.smile.cloud.points.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smile.cloud.points.config.SnowflakeConfig;
import com.smile.cloud.points.mapper.PointsMapper;
import com.smile.cloud.points.model.Points;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
public class PointsServiceImpl implements PointsService {

    @Autowired
    private PointsMapper pointsMapper;

    @Autowired
    private SnowflakeConfig snowflakeConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void increasePoints(OrderDTO order) {

        //入库之前先查询，实现幂等
        LambdaQueryWrapper<Points> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Points::getOrderNo, order.getOrderNo());
        if (pointsMapper.selectCount(queryWrapper) > 0) {
            log.info("积分添加完成，订单已处理。{}", order.getOrderNo());
        } else {
            Points points = new Points();
            points.setId(snowflakeConfig.snowflakeIdStr());
            points.setUserId(order.getUserId());
            points.setOrderNo(order.getOrderNo());
            BigDecimal money = order.getMoney();
            points.setPoints(money.intValue() * 10);
            points.setRemarks("商品消费共【" + money + "】元，获得积分" + points.getPoints());
            pointsMapper.insert(points);
            log.info("已为订单号码{}增加积分。", points.getOrderNo());
        }
    }
}
